<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<view class="content-bgc">
			<view class="b-con">
				<uni-forms :model="form" :rules="rules" ref="refForm" label-width="100px">
					<uni-forms-item label="照片">
						<uni-file-picker v-model="form.picture" file-mediatype="image" file-extname="png,jpg,jpeg" @select="select"
							return-type="object" title="只能上传jpg/png/jpeg文件，且建议大小不超过500kb"></uni-file-picker>
					</uni-forms-item>
					<uni-forms-item label="员工类型" name="classify" required>
						<uni-data-select v-model="form.classify" :localdata="classify_list" placeholder="请选择员工类型" mode="underline"
							:clear="false" />
					</uni-forms-item>
					<uni-forms-item label="工号">
						<uni-easyinput v-model="form.code" placeholder="请输入工号" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="姓名" name="full_name" required>
						<uni-easyinput v-model="form.full_name" placeholder="请输入姓名" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="手机号" name="mobile" required>
						<uni-easyinput v-model="form.mobile" type="number" placeholder="请输入手机号" class="iptBor" :inputBorder="false"
							@blur="blur('mobile')" />
					</uni-forms-item>
					<uni-forms-item label="职务" name="role" required>
						<uni-data-select v-model="form.role" multiple :localdata="role_list" placeholder="请选择职务" mode="underline"
							:clear="false" />
					</uni-forms-item>
					<uni-forms-item label="部门" name="group" required>
						<uni-data-select v-model="form.group" :localdata="group_list" placeholder="请选择部门" mode="underline"
							:clear="false" />
					</uni-forms-item>
					<uni-forms-item label="民族" name="nation">
						<uni-easyinput v-model="form.nation" placeholder="请输入民族" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="性别" name="sex" required>
						<uni-data-select v-model="form.sex" :localdata="[{ text: '男', value: 1 }, { text: '女', value: 2 }]"
							placeholder="请选择性别" mode="underline" :clear="false" />
					</uni-forms-item>
					<uni-forms-item label="身份证号码" name="idcard" required>
						<uni-easyinput v-model="form.idcard" type="idcard" placeholder="请输入身份证号码" class="iptBor"
							:inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="出生日期" name="birthday" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择合同结束时间" :clear-icon="false" v-model="form.birthday"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="地址">
						<uni-easyinput v-model="form.address" type="textarea" placeholder="请输入地址" />
					</uni-forms-item>
					<uni-forms-item label="婚姻状况" name="marriage">
						<uni-data-select v-model="form.marriage"
							:localdata="[{ text: '未婚', value: 1 }, { text: '已婚', value: 2 }, { text: '离异', value: 3 }]"
							placeholder="请选择婚姻状况" mode="underline" :clear="false" />
					</uni-forms-item>
					<uni-forms-item label="政治面貌" name="politics">
						<uni-easyinput v-model="form.politics" placeholder="请输入政治面貌" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="紧急联系人" name="urgency_full_name">
						<uni-easyinput v-model="form.urgency_full_name" placeholder="请输入紧急联系人" class="iptBor"
							:inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="紧急联系人电话" name="urgency_mobile">
						<uni-easyinput v-model="form.urgency_mobile" placeholder="请输入紧急联系人电话" @blur="blur('urgency_mobile')"
							class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="基本工资" name="salary">
						<uni-easyinput v-model="form.salary" type="number" placeholder="请输入基本工资" @blur="blur('salary')"
							class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="学历" name="degree">
						<uni-easyinput v-model="form.degree" placeholder="请输入学历" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="银行名称" name="bank_name">
						<uni-easyinput v-model="form.bank_name" placeholder="请输入银行名称" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="开户网点" name="bank_branch">
						<uni-easyinput v-model="form.bank_branch" placeholder="请输入开户网点" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="银行卡号" name="bank_code">
						<uni-easyinput v-model="form.bank_code" placeholder="请输入银行卡号" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="入职时间" name="in_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择入职时间" :clear-icon="false" v-model="form.in_date"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="合同开始时间" name="contract_start_date">
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择合同开始时间" :clear-icon="false"
								v-model="form.contract_start_date" :border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="合同结束时间" name="contract_end_date">
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择合同结束时间" :clear-icon="false"
								v-model="form.contract_end_date" :border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注">
						<uni-easyinput v-model="form.desc" type="textarea" placeholder="请输入备注" />
					</uni-forms-item>
					<u-button type="primary" text="提交" @click="save" />
				</uni-forms>
			</view>
		</view>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import acUserApi from '../../../api/account/ac_user'
import { BASE_URL } from '../../../common/request';

//页面标题
const pageInfo = reactive({
	navbarTitle: '员工管理',
	type: '',
	edit_id: null,
})

onLoad((option) => {
	get_group_list()
	get_role_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
	}
})

const classify_list = [
	{ text: '正式员工', value: 1 },
	{ text: '临时员工', value: 2 },
	{ text: '试用员工', value: 3 },
	{ text: '离职员工', value: 4 },
]

const refForm = ref(null);
const form = reactive({
	classify: null,
	picture: {},
	code: '',
	username: '',
	full_name: '',
	mobile: '',
	role: null,
	group: null,
	nation: '',
	sex: 1,
	idcard: '',
	birthday: '',
	address: '',
	marriage: 1,
	politics: '',
	urgency_full_name: '',
	urgency_mobile: '',
	salary: 0,
	degree: '',
	bank_name: '',
	bank_branch: '',
	bank_code: '',
	in_date: '',
	contract_start_date: null,
	contract_end_date: null,
	desc: ''
});
const fields = Object.keys(form)
const mobilePattern = {
	pattern: '^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$',
	errorMessage: '手机号格式不正确'
}
const rules = {
	classify: { rules: [{ required: true, errorMessage: '请选择员工类型' }] },
	username: { rules: [{ required: true, errorMessage: '请输入登陆账号' }] },
	role: { rules: [{ required: true, errorMessage: '请选择职务' }] },
	group: { rules: [{ required: true, errorMessage: '请选择部门' }] },
	birthday: { rules: [{ required: true, errorMessage: '选择出生日期' }] },
	in_date: { rules: [{ required: true, errorMessage: '选择入职时间' }] },
	full_name: { rules: [{ required: true, errorMessage: '请输入姓名' }] },
	mobile: {
		rules: [
			{ required: true, errorMessage: '请输入手机号' },
			mobilePattern
		]
	},
	urgency_mobile: {
		rules: [
			{ required: false },
			mobilePattern
		]
	},
	salary: { rules: [{ required: true, errorMessage: '请输入身份证号码' }, { validateFunction: positiveNum }] },
	idcard: { rules: [{ required: true, errorMessage: '请输入身份证号码' }] },
	sex: { rules: [{ required: true, errorMessage: '请选择性别' }] },
};
//单个校验
function blur(field) {
	refForm.value.validateField([field]).then().catch(err => { })
}

//表单校验，
function positiveNum(rule, value, data, callback) {
	const num = /^([1-9]\d*|0)(\.\d{1,2})?$/.test(value);
	if (!num) callback('请输入正数，且最多保留两位小数');
	return true
}


//详情
function get_detail(id) {
	acUserApi.staff_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields) //过滤表单需要的字段
		record.picture = {
			name: 'file.txt',
			extname: "txt",
			url: res.picture,
		}
		Object.assign(form, record)
	})
};

// 上传
const action = BASE_URL + '/file/';
const token = uni.getStorageSync("assecss_token");
function select({ tempFiles }) {
	uni.uploadFile({
		url: action, //仅为示例，非真实的接口地址
		filePath: tempFiles[0].path,
		name: 'file',
		header: {
			'Authorization': "JWT " + token
		},
		success: (files) => {
			const data = JSON.parse(files.data)
			form.picture = {
				name: 'file.txt',
				extname: "txt",
				url: data.file,
			}
		},
		fail: (err) => {
			uni.$u.toast('上传图片失败')
		}
	});
};
//提交表单
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		params.picture = params.picture.url
		if (pageInfo.type == 'add') {
			acUserApi.post_staff(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			acUserApi.patch_staff(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}
	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})

}

const group_list = ref([]);
function get_group_list() {
	acUserApi.get_group({ page: 1, page_size: 99999 }).then(res => {
		group_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
};

const role_list = ref([])
function get_role_list() {
	acUserApi.get_role({ page: 1, page_size: 99999, if_open: 1 }).then(res => {
		role_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
};

//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('ac_user');
		}
	})
};
</script>

<style lang="scss" scoped></style>